package com.jielihaofeng.netty.futurepromise;

import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * @author Johnnie Wind
 * @description Netty 中的 Future
 * @date 2021/11/10 09:57
 */
@Slf4j
public class TestNettyFuture {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup(2);
        Future<Integer> future = group.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws InterruptedException {
                log.debug("执行计算");
                Thread.sleep(1000);
                return 70;
            }
        });

        // 同步执行获取结果
        log.debug("等待结果");
        log.debug("结果是 {}", future.get());

        // 异步执行获取结果
        future.addListener(new GenericFutureListener<Future<? super Integer>>() {
            @Override
            public void operationComplete(Future<? super Integer> future) throws Exception {
                log.debug("接收结果：{}",future.getNow());
            }
        });

    }
}
